import { useState } from 'react'

import { Button } from '@/components/ui/button'
import { ChatModelEnum } from '@/configs/enums'

interface ChatButtonProps {
  threadId?: string
}

export default function ChatButton({ threadId }: ChatButtonProps) {
  const [text, setText] = useState('')
  const [message, setMessage] = useState('')
  const [generating, setGenerating] = useState(false)

  const handleSend = async () => {
    if (!message) return
    console.log('message', message)

    setGenerating(true)

    const res = await fetch('/api/chat/conversation', {
      method: 'POST',
      body: JSON.stringify({
        message,
        // model: ChatModelEnum.DEEPSEEK_REASONER,
        id: threadId,
      }),
    })

    if (!res.ok) return console.log('error', res.body)
    if (!res.body) return

    const reader = res.body.getReader()
    const decoder = new TextDecoder()

    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      const text = decoder.decode(value, { stream: true })
      console.log('text', text)
      setText(prev => prev + text)
    }

    setGenerating(false)

    setMessage('')
  }

  const handleStop = () => {
    setGenerating(false)
  }

  return (
    <div className="py-2 px-4">
      <p>{text}</p>
      <div className="border rounded-xl flex flex-col">
        <textarea
          style={{ border: 'none', outline: 'none' }}
          className="w-full resize-none py-2 px-4"
          placeholder="Ask me anything..."
          value={message}
          onChange={e => setMessage(e.target.value.trim())}
          onKeyDown={e => {
            if (e.key === 'Enter') {
              e.preventDefault()
              handleSend()
            }
          }}
        />
        <div className="flex items-center justify-between p-2">
          <div />
          {generating ? (
            <Button onClick={handleStop}>Stop</Button>
          ) : (
            <Button onClick={handleSend} disabled={!message}>
              Send
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}
